package com.javaweb.blogcite.util;

import com.javaweb.blogcite.pojo.Toc;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import static java.lang.Integer.parseInt;

public class TocGenerator {

    /**
     * 根据 html 生成 tocList
     * @param html
     * @return
     */
    public static List<Toc> generateTOC(String html) {
        Document doc = Jsoup.parse(html);

        List<Element> headings = doc.select("h1, h2, h3, h4, h5, h6");
        List<Toc> tocList = new ArrayList<>(); // 存储目录树结构
        Stack<Toc> stack = new Stack<>();// 跟踪目录层级

        for (Element heading : headings) {
            Integer level = parseInt(heading.tagName().substring(1));
            Toc cur = new Toc(heading.text(), level);

            while (!stack.isEmpty() && stack.peek().getLevel() >= level) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                stack.peek().addChild(cur);
            } else {
                tocList.add(cur);
            }
            stack.push(cur);
        }
        return tocList;
    }
}
